const app = getApp()

Page({
  data: {
    bestScore: 0,
    characterState: '',
    eyeState: '',
    mouthState: '',
    hairState: '',
    isAuthorized: false,
    userInfo: {
      avatarUrl: '',
      nickName: ''
    },
    showPrivacy: false,
    showAuthModal: false,
    showEditModal: false,
    tempNickname: ''
  },

  onLoad() {
    this.initAuth()
    this.initCharacter()
    
    // 监听隐私授权事件
    wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
      console.log('触发隐私授权事件:', eventInfo.referrer)
      this.setData({
        showPrivacy: true
      })
      this.resolvePrivacyAuthorization = resolve
    })

    // 加载用户最佳分数等数据
    this.loadUserData()
  },

  onShow() {
    this.initAuth()
  },

  // 初始化授权状态
  initAuth() {
    try {
      const cachedUserInfo = wx.getStorageSync('userInfo')
      if (this.validateUserInfo(cachedUserInfo)) {
        this.updateAuthState(cachedUserInfo)
      } else {
        this.resetAuthState()
      }
    } catch (e) {
      console.error('初始化授权状态失败:', e)
      this.resetAuthState()
    }
  },

  // 验证用户信息完整性
  validateUserInfo(userInfo) {
    return userInfo && 
           typeof userInfo === 'object' && 
           userInfo.avatarUrl && 
           userInfo.nickName
  },

  // 更新授权状态
  updateAuthState(userInfo) {
    // 更新全局状态
    app.globalData.userInfo = userInfo
    
    // 更新页面状态
    this.setData({
      isAuthorized: true,
      userInfo: userInfo
    }, () => {
      console.log('授权状态已更新:', this.data.isAuthorized)
      this.loadBestScore()
    })
  },

  // 重置授权状态
  resetAuthState() {
    this.setData({
      isAuthorized: false,
      userInfo: {
        avatarUrl: '',
        nickName: ''
      }
    })
  },

  // 选择头像
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    if (!avatarUrl) {
      wx.showToast({
        title: '获取头像失败',
        icon: 'none'
      })
      return
    }

    this.setData({
      'userInfo.avatarUrl': avatarUrl
    }, () => {
      console.log('头像已更新:', avatarUrl)
    })
  },

  // 输入昵称
  onInputNickname(e) {
    const nickName = e.detail.value.trim()
    if (!nickName) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }

    this.setData({
      'userInfo.nickName': nickName
    }, () => {
      console.log('昵称已更新:', nickName)
    })
  },

  // 处理授权
  handleAuth() {
    const { userInfo } = this.data
    if (!userInfo.avatarUrl || !userInfo.nickName) {
      wx.showToast({
        title: '请完善头像和昵称',
        icon: 'none'
      })
      return
    }

    // 保存用户信息到本地存储和全局数据
    wx.setStorageSync('userInfo', userInfo)
    const app = getApp()
    app.globalData.userInfo = userInfo
    
    // 关闭弹窗
    this.setData({
      showAuthModal: false
    }, () => {
      // 在回调中跳转，确保弹窗已经关闭
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/game/game'
        })
      }, 100)
    })
  },

  // 处理隐私授权
  handleAgreePrivacyAuthorization() {
    if (typeof this.resolvePrivacyAuthorization === 'function') {
      this.resolvePrivacyAuthorization({ 
        buttonId: 'agree-btn', 
        event: 'agree' 
      })
      this.setData({
        showPrivacy: false
      })
    }
  },

  // 加载最佳分数
  loadBestScore() {
    // 优先从云端获取最新分数
    wx.cloud.callFunction({
      name: 'getRanking',
      data: { limit: 1 },
      success: res => {
        if (res.result.success && res.result.myBestScore > 0) {
          this.setData({
            bestScore: res.result.myBestScore
          })
          app.globalData.bestScore = res.result.myBestScore
          wx.setStorageSync('bestScore', res.result.myBestScore)
        } else {
          this.loadLocalBestScore()
        }
      },
      fail: err => {
        console.error('获取云端分数失败', err)
        this.loadLocalBestScore()
      }
    })
  },

  // 加载本地最佳分数
  loadLocalBestScore() {
    const bestScore = wx.getStorageSync('bestScore') || 0
    this.setData({
      bestScore: bestScore
    })
    app.globalData.bestScore = bestScore
  },

  // 初始化角色状态
  initCharacter() {
    this.setData({
      characterState: '',
      eyeState: '',
      mouthState: '',
      hairState: ''
    })
  },

  // 角色出错动画
  showCharacterError() {
    this.setData({
      characterState: 'error',
      eyeState: 'dizzy',
      mouthState: 'sad',
      hairState: 'messy'
    })
    
    setTimeout(() => {
      this.initCharacter()
    }, 1000)
  },

  // 加载用户数据
  loadUserData() {
    const userInfo = wx.getStorageSync('userInfo')
    const bestScore = wx.getStorageSync('bestScore') || 0
    const app = getApp()
    
    // 同步到全局数据
    if (userInfo) {
      app.globalData.userInfo = userInfo
    }
    
    this.setData({
      userInfo: userInfo || {},
      bestScore
    })
  },

  // 开始游戏按钮点击处理
  startGame() {
    // 检查是否已授权
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo.nickName) {
      // 未授权，显示授权弹窗
      this.setData({
        showAuthModal: true
      })
      return
    }
    
    // 已授权，跳转到游戏页面
    wx.navigateTo({
      url: '/pages/game/game'
    })
  },

  // 测试云函数连接（调试用）
  testCloudFunction() {
    console.log('🧪 测试云函数连接...')
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log('🧪 云函数测试成功:', res)
        wx.showModal({
          title: '测试结果',
          content: `云函数正常\nOpenID: ${res.result.openid || '无'}\nSuccess: ${res.result.success}`,
          showCancel: false
        })
      },
      fail: err => {
        console.error('🧪 云函数测试失败:', err)
        wx.showModal({
          title: '测试失败',
          content: `错误: ${err.errMsg}`,
          showCancel: false
        })
      }
    })
  },

  // 开始PK
  startPK() {
    wx.navigateTo({
      url: '/pages/pk/pk'
    })
  },

  // 显示排行榜
  showRanking() {
    wx.navigateTo({
      url: '/pages/ranking/ranking'
    })
  },

  // 分享配置
  onShareAppMessage() {
    return {
      title: '必须反着做 - 魔性反应游戏',
      desc: '系统说左你要点右，但偶尔会突然反转规则坑你！快来挑战你的反向思维！',
      path: '/pages/index/index',
      imageUrl: '' // 可以设置分享图片
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '必须反着做 - 魔性反应游戏，挑战你的反向思维！',
      query: '',
      imageUrl: '' // 可以设置分享图片
    }
  },

  // 显示编辑昵称弹窗
  showEditNickname() {
    console.log('点击了修改昵称');
    
    this.setData({
      showEditModal: true,
      tempNickname: this.data.userInfo.nickName
    })
  },

  // 监听新昵称输入
  onInputNewNickname(e) {
    this.setData({
      tempNickname: e.detail.value
    })
  },

  // 取消编辑
  cancelEdit() {
    this.setData({
      showEditModal: false,
      tempNickname: ''
    })
  },

  // 确认编辑
  confirmEdit() {
    const { tempNickname, userInfo } = this.data
    if (!tempNickname.trim()) {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
      return
    }

    // 更新用户信息
    const newUserInfo = {
      ...userInfo,
      nickName: tempNickname
    }

    // 保存到本地和全局
    wx.setStorageSync('userInfo', newUserInfo)
    const app = getApp()
    app.globalData.userInfo = newUserInfo

    // 更新页面数据
    this.setData({
      userInfo: newUserInfo,
      showEditModal: false,
      tempNickname: ''
    })

    wx.showToast({
      title: '修改成功',
      icon: 'success'
    })
  }
}) 